#include "../lvgl/lvgl.h"
#include "img_playback.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>



P_Node_t Node_Init(char *name)
{
    P_Node_t NewNode = (Node_t *)calloc(1, sizeof(Node_t));

    if (name != NULL)
    {
        memcpy(NewNode->name, name, sizeof(NewNode->name));
    }

    NewNode->prev = NewNode;
    NewNode->next = NewNode;

    return NewNode;
}

void AddFun(P_Node_t head, P_Node_t NewNode)
{
    NewNode->next = head->next;
    head->next->prev = NewNode;
    head->next = NewNode;
    NewNode->prev = head;
}

void Search_Recursion(P_Node_t head, char *s, const char *Type)
{
    DIR *dp = opendir(s);
    if (dp == NULL)
    {
        perror("OPEN DIR ERROR");
        return;
    }
    while (1)
    {
        struct dirent *dir_for = readdir(dp);
        if (dir_for == NULL)
            break;

        if (dir_for->d_type == DT_DIR && strcmp(dir_for->d_name, ".") != 0 && strcmp(dir_for->d_name, "..") != 0)
        {
            char s1[256];
            snprintf(s1, sizeof(s1), "%s/%s", s, dir_for->d_name);
            Search_Recursion(head, s1, Type);
        }
        else
        {
            char *str = strrchr(dir_for->d_name, '.');
            if (str != NULL && strcmp(str, Type) == 0)
            {
                char src[256];
                snprintf(src, sizeof(src), "%s/%s", s, dir_for->d_name);
                P_Node_t NewNode = Node_Init(src);
                AddFun(head, NewNode);
            }
        }
    }
    closedir(dp);
    return;
}